#include "core_headers.hpp"
#include "Socket.hpp"
#include "EventLoop.hpp"
#include "Channel.hpp"

using AcceptorCallback = std::function<void(int)>;

class Acceptor
{
private:
	void HandleRead()
	{
		int newfd = _socket.Accept();
		if(newfd < 0)
		{
			return;
		}
		_acceptor_callback(newfd);
	}
	int CreateServer(uint64_t port)
	{
		int ret = _socket.CreateTcpServer(port);
		assert(ret == true);
		return _socket.Fd();
	}
public:
	// 1.创建监听套接字
	// 2.启动读事件监控
	// 3.事件触发后获取新链接
	// 4.为新连接创建Connection进行管理
	Acceptor(EventLoop *loop,uint64_t port)
		:_socket(CreateServer(port))
		,_loop(loop)
		,_channels(_loop,_socket.Fd())
	{
		/*不能将启动读事件监控，放到构造函数中，必须在设置回调函数后，再去启动*/
        /*否则有可能造成启动监控后，立即有事件，处理的时候，回调函数还没设置：新连接得不到处理，且资源泄漏*/
		_channels.SetReadCallback(std::bind(&Acceptor::HandleRead,this));
		// _channels.EnableReadableEvent();
	}
	void SetAcceptorCallback(const AcceptorCallback &cb)
	{
		_acceptor_callback = cb;
	}
	void Listen()
	{
		_channels.EnableReadableEvent();
	}
private:
	Socket _socket;
	EventLoop *_loop;
	Channel _channels;
	AcceptorCallback _acceptor_callback;
};